package com.cv.framework.email.core.service;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.cv.framework.common.exception.ServerException;
import com.cv.framework.common.pojo.Result;
import com.cv.framework.email.config.CvEmailProperties;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.mail.SimpleEmail;
import org.springframework.data.redis.core.StringRedisTemplate;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

import static com.cv.framework.common.pojo.Result.success;
import static com.cv.framework.email.core.redis.RedisKeyConstants.EMAIL_CODE;

/**
 * 邮箱业务层接口实现类
 *
 * @author Charles_XDXD
 */
@RequiredArgsConstructor
@Slf4j
public class CvEmailServiceImpl implements CvEmailService {

    @Resource
    private final CvEmailProperties emailProperties;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result<String> sendEmail(String email) {
        String uuid = IdUtil.fastSimpleUUID();

        try {
            SimpleEmail mail = new SimpleEmail();
            String code = IdUtil.fastSimpleUUID().substring(0, 6);
            mail.setHostName(emailProperties.getHostName());
            mail.setAuthentication(emailProperties.getUsername(), emailProperties.getPassword());
            mail.setFrom(emailProperties.getEmail(), emailProperties.getName());
            mail.setSSLOnConnect(true);
            mail.addTo(email);
            mail.setSubject(emailProperties.getSubject());
            mail.setMsg("尊敬的用户:你好!\n 验证码为:" + code + "\n" + "     (有效期为三分钟)");
            mail.send();

            String key = String.format(EMAIL_CODE, email, uuid);
            stringRedisTemplate.opsForValue().set(key, code, 3, TimeUnit.MINUTES);
        } catch (Exception e) {
            log.error("发送邮件失败: ", e);
            throw new ServerException(500, "发送邮件失败");
        }

        return success(uuid);
    }

    @Override
    public Result<Boolean> checkEmail(String uuid, String email, String code) {
        String key = String.format(EMAIL_CODE, email, uuid);

        String storeCode = stringRedisTemplate.opsForValue().get(key);

        if (StrUtil.isNotEmpty(storeCode) && storeCode.equalsIgnoreCase(code)) {
            return success(true);
        }

        stringRedisTemplate.delete(key);
        return success(false);
    }

}
